package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * arr
 * 2165. 重排数字的最小值
 *
 * @author liw
 * @version 1.0
 * @date 2022/2/11 15:31
 */
public class SmallestNumber {


    public static void main(String[] args) {
        SmallestNumber test = new SmallestNumber();

        // 0
//        long a = 0L;

        // 1023
//        long a = 3210L;

        // 0
        long a = -3210L;

        long l = test.smallestNumber(a);
        System.out.println(l);
    }

    public long smallestNumber(long num) {
        if (num == 0L) {
            return 0L;
        }
        boolean flag = num > 0L;
        if (flag) {
            char[] chars = String.valueOf(num).toCharArray();
            Arrays.sort(chars);
            int length = chars.length;
            if (chars[0] == '0') {
                for (int i = 0; i < length; i++) {
                    if (chars[i] != '0') {
                        chars[0] = chars[i];
                        chars[i] = '0';
                        break;
                    }
                }
            }
            return Long.parseLong(String.valueOf(chars));
        } else {
            num *= -1L;
            char[] chars = String.valueOf(num).toCharArray();
            Arrays.sort(chars);
            int length = chars.length;
            int l = length >> 1;
            for (int i = 0; i < l; i++) {
                char c = chars[i];
                chars[i] = chars[length - 1 - i];
                chars[length - 1 - i] = c;
            }
            return Long.parseLong(String.valueOf(chars)) * -1L;
        }
    }

}
